package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.RegexUtils.isPhoneInvalid;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校验手机号
        if (isPhoneInvalid(phone)){
            return Result.fail("手机号不正确");
        }
        String code = RandomUtil.randomNumbers(6);//生成6位数的验证码
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);//将验证码存入redis
        log.info("发送的短信验证码为:"+code);
        return Result.ok();
    }

    @Override
    public Result signDays() {
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now=LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key=userId+format;
        int dayOfMonth = now.getDayOfMonth();//获取今天是这个月的第几天
        //获取本月所有的签到记录
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)

        );
        if (result==null||result.isEmpty()){
            return Result.ok();

        }
        Long aLong = result.get(0);//我们只插入了第一个结果
        int count=0;
        if (aLong==null||aLong==0){
            return Result.ok(0);
        }
        while (true){
            //进行与运算，判断最后一位是0还是1
            if ((aLong&1)==0){
                count=0;
               break;
            }
            count++;
            //右移一位
            count >>>=1;
        }
        return Result.ok(count);
    }

    @Override
    public Result sign() {
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now=LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key=userId+format;
        int dayOfMonth = now.getDayOfMonth();//获取今天是这个月的第几天
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth,true);
        return Result.ok();



    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        //判断是否不匹配，不匹配返回true
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号不正确");
        }
        //校验验证码,从redis中取验证码
        String s = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY+phone);//
        String code = loginForm.getCode();
        if (s==null||!s.equals(code)) {
            return Result.fail("验证码不正确");
        }
        User user = query().eq("phone", phone).one();//相当于一条sql语句,select * form tb_user where phone=?
        //判断用户是否存在.不存在则创建一个用户
        if (user== null) {
           user = createUserWithPhone(phone);
        }
        String token= UUID.randomUUID().toString();//生成token,作为登录令牌
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);//将user对象转为userDto对象
        Map<String,Object> userMap=BeanUtil.beanToMap(userDTO,new HashMap<>(),//将userDto对象转为map集合
        CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((filedName,fieldValue) -> fieldValue.toString()));

        String tokenKey=token+LOGIN_USER_KEY;
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL, TimeUnit.SECONDS);//间隔一定时间刷新token有效期。
        return Result.ok(token);//将token返回给前端
    }

    private User createUserWithPhone(String phone) {
         User user=new User();
         user.setPhone(phone);
         user.setNickName("user"+RandomUtil.randomString(4));//生成用户名
         save(user);//存入数据库
         return user;
    }
}
